package me.numark.fragments;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.marshalchen.ultimaterecyclerview.ObservableScrollState;
import com.marshalchen.ultimaterecyclerview.ObservableScrollViewCallbacks;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.ui.VerticalSwipeRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.numark.R;
import me.numark.activities.CommentBaseActivity;
import me.numark.model.Feed;
import me.numark.model.Topic;
import me.numark.model.TopicListResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.view.TopicAdapter;

/**
 * Created by Evan on 15/7/24.
 */
public class CommentsFragment extends BaseListFragment {

    private static final String ARG_TYPE = "type";
    private static final String ARG_ID = "feedId";
    private static final String ARG_NEWSID = "newsId";
    public static final String ARG_FROM_NOTICE = "need_hint";
    private int feedType;
    private long feedId;
    private long newsId;
    private boolean needHint;
    public static final int TYPE_ARTICLE_MARK = 0;
    public static final int TYPE_ARTICLE_COMMENT = 1;
    public static final int TYPE_MARK_COMMENT = 2;
    VerticalSwipeRefreshLayout swipeRefreshLayout;
    TopicAdapter mTopicAdapter;

    public void setRefreshLayout(VerticalSwipeRefreshLayout refreshLayout){
        swipeRefreshLayout = refreshLayout;
    }

    public static CommentsFragment newInstance(int feedType, long feedId ,long newsId,boolean fromNotice){
        CommentsFragment fragment = new CommentsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_TYPE, feedType);
        args.putLong(ARG_ID, feedId);
        args.putLong(ARG_NEWSID,newsId);
        args.putBoolean(ARG_FROM_NOTICE,fromNotice);
        fragment.setArguments(args);
        return fragment;
    }
    public static CommentsFragment newInstance(int feedType, long feedId ) {
        CommentsFragment fragment = new CommentsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_TYPE, feedType);
        args.putLong(ARG_ID, feedId);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            feedType = getArguments().getInt(ARG_TYPE, -1);
            feedId = getArguments().getLong(ARG_ID, 0);
            newsId = getArguments().getLong(ARG_NEWSID,0);
            needHint = getArguments().getBoolean(ARG_FROM_NOTICE,false);
        }
        dataList = new ArrayList();
        if (getActivity() instanceof CommentBaseActivity)
            mTopicAdapter = new TopicAdapter((CommentBaseActivity) getActivity(), dataList, this,0,Constants.TOPICTYPE_NONE);
        else
            mTopicAdapter = new TopicAdapter(null, dataList, this,0,Constants.TOPICTYPE_NONE);
        mAdapter = mTopicAdapter;
        if (feedType == TYPE_ARTICLE_MARK) {
            empty_text = R.string.empty_marks;
        } else {
            empty_text = R.string.empty_comments;
            mTopicAdapter.commentable = true;
        }
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(commentBroadcastReceiver,
                new IntentFilter(Constants.ACTION_TOPIC_DELETED));

    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(commentBroadcastReceiver);
        super.onDestroy();

    }

    @Override
    public void initUI(View view) {
        super.initUI(view);
        toolbar.setVisibility(View.GONE);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (needHint) {

                }else {
                    //mListener.onClickComment(null);
                }
            }
        });

        recyclerView.setDefaultOnRefreshListener(null);
        recyclerView.mSwipeRefreshLayout.setEnabled(false);
        recyclerView.mSwipeRefreshLayout.setRefreshing(false);
        recyclerView.mSwipeRefreshLayout = swipeRefreshLayout;
        recyclerView.mSwipeRefreshLayout.setEnabled(false);
        recyclerView.setDefaultOnRefreshListener(this);

    }


    @Override
    public void loadMore(int itemsCount, int maxLastVisiblePosition) {
        super.loadMore(itemsCount, maxLastVisiblePosition);
        loadData(itemsCount);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        loadData(0);
    }

    protected String getFeedUrl() {
        switch (feedType) {
            case TYPE_ARTICLE_MARK:
                return String.format(NetworkConstants.ARTICLE_MARK_URL, Global.getCurrentUid(), feedId);
            case TYPE_ARTICLE_COMMENT:
                return String.format(NetworkConstants.ARTICLE_COMMENT_URL, Global.getCurrentUid(), feedId);
            case TYPE_MARK_COMMENT:
                return String.format(NetworkConstants.MARK_COMMENT_URL, Global.getCurrentUid(), feedId);
            default:
                return null;
        }
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, TopicListResponse.class);
    }

    @Override
      protected void addDataToList(BaseResponse response, boolean isNew) {
        TopicListResponse resp = (TopicListResponse) response;
        if (isNew) {
            mTopicAdapter.clear();
        }
        mTopicAdapter.append(resp.data);
        setHasMore(resp.has_more);
    }

    protected void loadData(final int start) {
        if (needLogin && Global.currentUser == null) {
            endRefreshing();
            showEmptyView();
            return;
        }
        new RequestServerTask<TopicListResponse>(TopicListResponse.class) {
            @Override
            protected String requestServer() {

                Map<String, Object> params = new HashMap<String, Object>();
                Map<String,Object> postParams = new HashMap<String, Object>();
                postParams.put("nid",newsId);
                params.put("start", String.valueOf(start));
                params.put("limit", String.valueOf(Constants.PAGE_SIZE));
                if (start > 0 && lastResponseTime > 0) {
                    params.put("time", String.valueOf(lastResponseTime));
                }
                return HttpUtil.post(getFeedUrl(), params, postParams, null);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(TopicListResponse result) {
                bindData(result, start == 0);
            }
        }
                .setSnackbarView(rootView)
                .start();
    }

    @Override
    protected void bindData(BaseResponse response, boolean isNew) {
        super.bindData(response, isNew);
        recyclerView.hideEmptyView();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnCommentsFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private OnCommentsFragmentInteractionListener mListener = null;

    public interface OnCommentsFragmentInteractionListener {
        public void onClickComment(Topic topic);
    }

    BroadcastReceiver commentBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_TOPIC_DELETED.equals(intent.getAction())) {
                long tid = intent.getLongExtra(Constants.COMMENT_TID_EXTRA, 0);
                if (tid != 0) {
                    for (int i = 0; i < dataList.size(); i++) {
                        Topic topic = (Topic) dataList.get(i);
                        if (topic.tid == tid) {
                            mAdapter.remove(dataList, i);
                            break;
                        }
                    }
                }
            }
        }
    };
}
